package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserFavor;
import cn.wolfcode.wolf2w.query.UserFavorQueryObject;
import cn.wolfcode.wolf2w.repository.UserFavorRepository;
import cn.wolfcode.wolf2w.service.IUserFavorService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserFavorServiceImpl implements IUserFavorService {

    @Autowired
    private UserFavorRepository userFavorRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(UserFavor userFavor) {
        userFavor.setId(null);
        userFavorRepository.save(userFavor);
    }

    @Override
    public void delete(String id) {
        userFavorRepository.deleteById(id);
    }

    @Override
    public void update(UserFavor userFavor) {
        userFavorRepository.save(userFavor);
    }

    @Override
    public UserFavor get(String id) {
        return userFavorRepository.findById(id).orElse(null);
    }

    @Override
    public List<UserFavor> list() {
        return userFavorRepository.findAll();
    }

    @Override
    public Page<UserFavor> query(UserFavorQueryObject qo) {
        // 创建拼接对象
        Query query = new Query();
        // 使用PageRequest.of,传入当前页 - 1 (记得-1, 因为当前页从0开始), 页面显示条数, 排序规则, 排序的列
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, qo, query, pageable, UserFavor.class);
    }

    @Override
    public void updateUserFavorStatis(UserFavor userFavor) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userFavor.getUserId()));
        Update update = new Update();
        update.set("strategyIds", userFavor.getStrategyIds());
        template.upsert(query, update, UserFavor.class);
    }


}
